<?php
/**
 * 设备盒子操作控制器
 */
namespace app\api\controller;

use app\common\controller\Common;

class Equipment extends Base
{
    public function list()
    {
        try {
            $param  = $this->param;
            $condition = !empty($param['condition']) ? $param['condition'] : 'connection';
            $keyword = !empty($param['keyword']) ? $param['keyword'] : '';
            $status = isset($param['status'])? $param['status'] : 1;
            $page = !empty($param['page']) ? $param['page'] : '1';
            $limit = !empty($param['limit']) ? $param['limit'] : '10';
            $equ_model = Model('Equipment');
            $data = $equ_model->getList($condition, $keyword, $page, $limit, $status);
            return resultArray(['data' => $data]);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
    }

    /**
     * 设备盒子状态查询列表,包含模糊搜索
     * 参数 
     * status:状态 , 默认1
     */
    public function listStatus($status = '1', $limit = '10', $page = '1', $match = "")
    {
        //创建equipment模型实例
        $model = model('equipment');
        $status = input('param.status') ? input('param.status') : $status;
        $limit = input('param.limit') ? input('param.limit') : $limit;
        $page = input('param.page') ? input('param.page') : $page;
        $match = input('param.match') ? input('param.match') : $match;
        try {
            //查询列表by status
            $result = $model->fuzzySearchList(['status' => $status], $match, $limit, $page);
            //查找列表的总数量,为分页做准备
            $total = $model->where(['status' => $status])->where('title|mac|serial', 'like', '%' . $match . '%')->count();
            $total_pages = ceil($total / $limit);
            //设置正确的验证状态值
            $status_arr = ['未授权', '已授权'];
            $status_conn = [2=>'登出',1=>'登录',3=>'异常断开'];
            $type = [1 => '终端', 2 => '校正端'];
            if (!empty($result)) {
                foreach ($result as $key => $value) {
                    $result[$key]['detail'] = $status_arr[$value['status']];
                    $result[$key]['connDetail'] = $status_conn[$value['connection']];
                    $result[$key]['typeDetail'] = $type[$value['type']];
                }
            }
            $data = [
                'list' => $result,
                'total' => $total,
                'totalPage' => $total_pages
            ];
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 设备盒子授权状态修改
     * 参数 
     * status   要修改成的状态
     * id       主键id
     */
    public function updateStatus()
    {
        //前端获取post数据
        if (request()->isPost()) {
            try {
                $model = model('equipment');
                $status = input('param.status');
                $data = ['status' => $status];
                $id = input('param.equipmentid');
                $data['update_time'] = time();
                $count = $model->where('status', '=', 1)->count();
                if($status == 1 && $count >= config('AUTHORIZATION_CEIL'))
                {
                    return resultArray(['error' => '授权已达到上限，请先取消授权']);
                }
                $result = $model->updateById($data, $id);
                if ($result) {
                    if ($status == 0) {
                        //如果为取消授权状态，更改状态后，将设备缓存中的mac地址删除
                        $mac = $model->get($id)->mac;
                        $authorization_mac = cache('authorization_mac');
                        $key = $authorization_mac? array_search($mac, $authorization_mac) : false;
                        if(!($key === false))
                        {
                            array_splice($authorization_mac, $key, 1);
                            cache('authorization_mac', $authorization_mac);
                        }
                    }else if($status == 1){
                        //如果为授权状态，更改状态后，将mac地址加入设备缓存中的
                        $mac = $model->get($id)->mac;
                        $authorization_mac = cache('authorization_mac');
                        $authorization_mac = $authorization_mac ? array_merge($authorization_mac, (array)$mac) : [$mac];
                        cache('authorization_mac', $authorization_mac);
                    }
                    return resultArray(['data' => '']);
                }
            } catch (\Exception $e) {
                //return resultArray(['error' => $e->getMessage()]);
                return resultArray(['error' => '更改失败']);
            }
        }
        return resultArray(['error' => '更改失败']);
    }
}
